<template>
	<view class="cu-w-100">
		<cu-navbar v-if="showLeftClick" title="流水" :placeholder="true" @leftClick="vk.navigateBack()" :showLeft="true"
			:leftIconColor="{color:'#FFF'}" :titleStyle="{color:'#FFF'}" :style="getBackgroundStyle"
			bgColor="rgb(255,255,255,0)"></cu-navbar>
		<cu-navbar v-if="!showLeftClick" title="流水" :placeholder="true" :titleStyle="{color:'#FFF'}"
			:style="getBackgroundStyle" bgColor="rgb(255,255,255,0)"></cu-navbar>
		<view class="cu-w-100 cu-p-20 cu-border-box">
			<u-sticky offset-top="88">
				<view v-if="accountBook !== undefined" class="cu-w-100 cu-border-box">
					<view class="cu-w-100 cu-text-white">
						<cu-card :style="cardStyle">
							<view class="cu-w-100 cu-row cu-j-sb cu-py-10">

								<view class="cu-font-weight cu-text-info cu-pr-20">
									<u-tag :text="accountBook.accountType % 2 == 0 ? '共享账本' : '个人账本'" plain size="mini"
										shape="circle"
										:type="accountBook.accountType % 2 == 0 ? 'success' : 'primary'"></u-tag>
								</view>
								<view class="cu-font-weight cu-w-100 cu-flex-1 cu-j-start cu-ovr-hdn">
									{{accountBook.accountBookName}}
								</view>
								<view @click="pickerShow = true">
									<u-icon name="list-dot" color="#FFF" size="24"></u-icon>
									<cu-picker @confirm="pickerConfirm()" @close="pickerShow = false"
										@cancel="pickerShow = false" :show="pickerShow" :columns="[allAccountBooks]"
										keyName="accountBookName" :defaultIndex="[selectAccountBookIndex]"></cu-picker>
								</view>
							</view>
							<view class="cu-w-100 cu-row cu-j-start cu-py-10 cu-a-center">
								<view class="cu-px-10 cu-font-weight cu-font-big">结余：</view>
								<view class="cu-font-weight cu-py-10">
									<u-count-to color="#FFF" fontSize="32" :startVal="0"
										:endVal="accountBook.surplus | fmtAmount" :useEasing="false" :decimals="2"
										:duration="500" separator=","></u-count-to>
								</view>
							</view>
							<view class="cu-w-100 cu-row cu-j-sb">
								<view class="cu-span24-18 cu-row cu-j-start cu-py-10 cu-a-center">
									<view class="cu-px-10">丨 总收入：</view>
									<view class="cu-font-weight cu-px-10">
										<u-count-to color="#dd524d" :startVal="0" font-size="16"
											:endVal="accountBook.totalRevenue | fmtAmount" :useEasing="false"
											:decimals="2" :duration="500" separator=","></u-count-to>
									</view>
								</view>
								<view class="cu-span24-6 cu-row cu-j-start cu-py-10 cu-a-center">
									共<view class="cu-px-10"> <u-count-to color="#17a2b8" :startVal="0" font-size="16"
											:endVal="accountBook.totalCount" :useEasing="false" :duration="500"
											separator=","></u-count-to> 笔</view>
								</view>
							</view>
							<view class="cu-w-100 cu-row cu-j-sb">
								<view class="cu-span24-18 cu-row cu-j-start cu-py-10 cu-a-center">
									<view class="cu-px-10">丨 总支出：</view>
									<view class="cu-font-weight cu-px-10">
										<u-count-to color="#8bc34a" :startVal="0" font-size="16"
											:endVal="accountBook.totalEcpenditure | fmtAmount" :useEasing="false"
											:decimals="2" :duration="500" separator=","></u-count-to>
									</view>
								</view>
								<view class="cu-span24-6 cu-row cu-j-start cu-py-10 cu-a-center">
									共 <view class="cu-px-10"><u-count-to color="#17a2b8" :startVal="0" font-size="16"
											:endVal="accountBook.totalPersion" :useEasing="false" :duration="500"
											separator=","></u-count-to> 人记账</view>
								</view>
							</view>
						</cu-card>
					</view>
				</view>
			</u-sticky>
			<!-- 收支报告 -->
			<view class="cu-w-100 cu-border-box cu-mt-20">
				<cu-statements :statements="statements"></cu-statements>
			</view>

			<!-- 流水 -->
			<view class="cu-w-100 cu-border-box cu-mt-20 cu-mb-50">
				<cu-card>
					<view class="cu-w-100 cu-row cu-font-weight cu-j-sb cu-a-center cu-font-big cu-py-20 cu-mb-20">
						<view class="cu-span24-12 cu-row">
							<view style="border-left: 10rpx solid #CCC; margin-right: 20rpx;"></view>
							流水明细
						</view>
						<view class="cu-span24-12 cu-font cu-row cu-j-end cu-a-center">
							显示备注：<u-switch v-model="closeRemark" @change="!closeRemark" size="20" ></u-switch>
						</view>
					</view>
					<block v-for="(item,idx) in dataList" :key="idx">
						<view class="cu-w-100 cu-row">
							<view class="cu-w-100 cu-row cu-j-sb cu-py-20 cu-font-sm">
								<view class="cu-w-100 cu-row" v-if="showDataDateMark(idx)">
									<view class="cu-span24-6 cu-text-light-muted">{{item.dataInf.date}}</view>
									<view class="cu-span24-18 cu-text-light-muted cu-row cu-j-end">
										<view class="cu-px-10">支出：{{getDateAmount(idx, "true")}}</view>
										<view class="cu-px-10">收入：{{getDateAmount(idx, "false")}}</view>
									</view>
								</view>
								<view class="cu-w-100 cu-row cu-j-sb cu-a-center cu-pt-20">
									<view class="cu-span24-6 cu-row cu-j-start cu-ovr-hdn cu-a-center">
										<u-avatar size="24" :src="item.dataInf.userInf.avatar"></u-avatar>
										<view class="cu-px-10">{{item.dataInf.userInf.nickname}}</view>
									</view>
									<view class="cu-span24-18 cu-row cu-j-sb cu-ovr-hdn cu-a-center">
										<view>{{item.dataInf.createTime | formatTime}}</view>
										<view class="cu-row cu-j-start cu-a-center"><cu-icon custom-prefix="iconfont" slot="icon" size="24" :name="item.dataInf.icon"></cu-icon><view class="cu-px-20">{{item.dataInf.iconName}}</view></view>
										<view>{{item.dataInf.amount | fmtAmount}}</view>
										<u-icon name="list-dot" color="#CCC" size="24" @click="selectDataBtn(idx)"></u-icon>
									</view>
								</view>
							</view>
							<view v-if="closeRemark && vk.myfn.isNotEmpty(item.dataInf.remarks)" class="cu-w-100 cu-text-light-muted cu-row cu-j-start cu-p-10 cu-font-sm">
								{{item.dataInf.remarks}}
							</view>
						</view>
					</block>
					<view v-if="dataList.length > 0" class="cu-my-40">
						<u-loadmore :status="loadMore.status" :loading-text="loadMore.loadingText" :loadmore-text="loadMore.loadmoreText"
							:nomore-text="loadMore.nomoreText" :color="main" :lineColor="main" line/>
					</view>
				</cu-card>
				
				<u-popup :show="show" mode="left" @close="close" @open="open" :customStyle="{width:'150%'}">
					<view class="cu-pt-50 cu-mt-50" v-if="selectData">
						<cu-card>
							<view class=" cu-px-20">
								<view class="cu-w-100 cu-row cu-j-start cu-a-center cu-pt-20">
									<view class="cu-font-weight cu-span24-8 cu-row cu-j-start cu-ovr-hdn cu-a-center">
										用户
									</view>
									<view class="cu-span24-16 cu-row cu-j-start cu-ovr-hdn cu-a-center">
										<u-avatar size="24" :src="selectData.dataInf.userInf.avatar"></u-avatar>
										<view class="cu-px-10">{{selectData.dataInf.userInf.nickname}}</view>
									</view>
								</view>
							</view>
							<view class=" cu-px-20">
								<view class="cu-w-100 cu-row cu-j-start cu-a-center cu-pt-20">
									<view class="cu-font-weight cu-span24-8 cu-row cu-j-start cu-ovr-hdn cu-a-center">
										时间
									</view>
									<view class="cu-span24-16 cu-row cu-j-start cu-ovr-hdn cu-a-center">
										<view>{{selectData.dataInf.createTime | formatTime}}</view>
									</view>
								</view>
							</view>
							<view class=" cu-px-20">
								<view class="cu-w-100 cu-row cu-j-start cu-a-center cu-pt-20">
									<view class="cu-font-weight cu-span24-8 cu-row cu-j-start cu-ovr-hdn cu-a-center">
										分类
									</view>
									<view class="cu-span24-16 cu-row cu-j-start cu-ovr-hdn cu-a-center">
										<view class="cu-row cu-j-start cu-a-center"><cu-icon custom-prefix="iconfont" slot="icon" size="24" :name="selectData.dataInf.icon"></cu-icon><view class="cu-px-20">{{selectData.dataInf.iconName}}</view></view>
									</view>
								</view>
							</view>
							<view class=" cu-px-20">
								<view class="cu-w-100 cu-row cu-j-start cu-a-center cu-pt-20">
									<view class="cu-font-weight cu-span24-8 cu-row cu-j-start cu-ovr-hdn cu-a-center">
										金额
									</view>
									<view class="cu-span24-16 cu-row cu-j-start cu-ovr-hdn cu-a-center">
										<view>{{selectData.dataInf.amount | fmtAmount}}</view>
									</view>
								</view>
							</view>
						</cu-card>
						<cu-card :style="cardStyle1">
							<u-cell-group :border="false">
								<u-cell title="编辑"  @click="clickCardItem('edit')" >
									<cu-icon custom-prefix="iconfont" slot="icon" size="24" name="icon-bianji"></cu-icon>
								</u-cell>
								<u-cell title=" 删除" :border="false" @click="clickCardItem('del')">
									<cu-icon slot="icon" size="24" custom-prefix="iconfont" name="icon-shanchu"></cu-icon>
								</u-cell>
							</u-cell-group>
						</cu-card>
					</view>
				</u-popup>
			</view>
		
			<u-modal :show="showModal" @close="closeModal" @cancel="closeModal" @confirm="confirmModal" ref="uModal"
				:title="modal.title" :content='modal.content' :zoom="true" :showCancelButton="true"
				:closeOnClickOverlay="true"></u-modal>
		</view>
	</view>
</template>

<script>
	let vk = uni.vk;
	export default {
		props: {
			showLeftClick: {
				type: Boolean,
				default: false
			},
			userInfo: {
				type: Object,
				default: {
					"avatar": "",
					"nickname": ""
				}
			},
			reachBottomTemp: {
				type: Number,
				default: 0
			},
			flowDataReload: {
				type: Number,
				default: 0
			},
		},
		watch: {
			// 监听默认索引的变化，重新设置对应的值
			reachBottomTemp: {
				immediate: true,
				handler(n) {
					if (!this.enqrDataByPage.hasMore) return; // 无更多数据时直接返回
					let that = this
					this.loadMore.status = "loading"
					this.enqrBookDataList()
				}
			},
			flowDataReload: {
				immediate: true,
				async handler(n) {
					// 关闭
					this.show = false
					this.showModal = false;
					this.allAccountBooks= vk.getVuex('$accountbook.allAccountBooks');
					this.typeDataPickerData= vk.getVuex('$typeData.typeDataPickerData');
					if (!vk.myfn.isEmpty(this.allAccountBooks) && this.reloadMark === true) {
						this.reloadMark = false
						await this.$store.dispatch('$accountKeepData/clearEnqrData');
						await this.enqrBookDataList();
						await this.enqrStatements()
						this.reloadMark = true
					}
					
				}
			},
		},
		computed: {
			getBackgroundStyle() {
				if (vk.myfn.isEmpty(this.userInfo)) {
					this.vk.myfn.gotoPage('/pages/oauth/login/index', 'navigate')
				}
				let style = {};
				style.background = "linear-gradient(45deg, " + this.main + ", " + this.secondary + ")";
				// 合并用户传递的背景色对象
				Object.assign(style, this.backgroundStyle);
				return style;
			},
			accountBook() {
				if(this.enqrDataByPage && this.enqrDataByPage.hasMore) {
					this.loadMore.status = "loadmore"
				}
				else {
					this.loadMore.status = " nomore"
				}
				if (vk.myfn.isNotEmpty(this.allAccountBooks)) {
					return this.allAccountBooks[this.selectAccountBookIndex]
				}
				return undefined
			},
			
		},
		filters: {
			formatDate(value) {
				if (!value) return '';
				const date = new Date(value);
				return date.toLocaleString('zh-CN', {
					year: 'numeric',
					month: 'long',
					day: 'numeric',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit',
					hour12: false
				});
			},
			formatTime(value) {
				if (!value) return '';
				// 创建 Date 对象（假设时间戳是毫秒级，如果是秒级需先 *1000）
				if(typeof value === 'string') {
					value = Number(value)
				}
				const date = new Date(value);
				// 提取时间部分并补零
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				// const seconds = String(date.getSeconds()).padStart(2, '0');
				// 拼接格式
				return `${hours}:${minutes}`;
			},
			fmtAmount(value) {
				if (!value) return 0;
				let rtn = value / 100
				return rtn.toFixed(2);
			},
		},
		data() {
			// 页面数据变量
			return {
				main: vk.getVuex('$app.color.main'),
				secondary: vk.getVuex('$app.color.secondary'),
				backgroundStyle: {
					color: "#FFF"
				},
				reloadMark: true,
				cardStyle: {
					"marginTop": "20rpx",
					"background": "url(/pages/accountbook/static/111.png)"
				},
				cardStyle1: {
					"marginTop": "20rpx",
				},
				allAccountBooks: vk.getVuex('$accountbook.allAccountBooks'),
				typeDataPickerData: vk.getVuex('$typeData.typeDataPickerData'),
				selectAccountBookIndex: vk.getVuex('$accountKeepData.selectAccountBookIndex'),
				pickerShow: false,
				statements: {
					today: {
						date: Date.now(),
						totalRevenue: 0,
						totalEcpenditure: 0
					},
					week: {
						startDate: Date.now(),
						endDate: Date.now(),
						totalRevenue: 0,
						totalEcpenditure: 0
					},
					month: {
						startDate: Date.now(),
						endDate: Date.now(),
						totalRevenue: 0,
						totalEcpenditure: 0
					}
				},
				closeRemark: true,
				dataList:vk.getVuex('$accountKeepData.dataList'),
				enqrDataByPage: vk.getVuex('$accountKeepData.enqrDataByPage'),
				loadMore: {
					status: 'loadmore',
					loadingText: '努力加载中',
					loadmoreText: '上拉加载更多',
					nomoreText: '实在没有了'
				},
				show: false,
				selectIndex: 0,
				selectData: undefined,
				showModal: false,
				modelType: "",
				modal: {
					title: '温馨提示',
					content: '确认删除么？'
				},
			};
		},
		// 监听 - 页面每次【加载时】执行(如：前进)
		onLoad(options = {}) {
			vk = uni.vk;
			this.options = options;
			this.init(options);
			this.$store.dispatch('$accountKeepData/clearEnqrData');
			this.enqrBookDataList();
		},
		// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
		onReady() {

		},
		// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
		onShow() {
		},
		// 监听 - 页面每次【隐藏时】执行(如：返回)
		onHide() {

		},
		// 函数
		methods: {
			// 页面数据初始化函数
			init(options) {
				this.main = vk.getVuex('$app.color.main');
				this.secondary = vk.getVuex('$app.color.secondary');
			},
			async pickerConfirm(e) {
				this.pickerShow = false
				this.selectAccountBookIndex = e.indexs[0]
				this.$store.dispatch('$accountKeepData/clearEnqrData');
				await this.reloadData();
				await this.enqrStatements()
			},
			async enqrStatements() {
				const that = this
				const accountBook = this.allAccountBooks[this.selectAccountBookIndex]
				await vk.callFunction({
					url: 'client/accounting/record/kh/getStatements',
					title: '请求中...',
					data: {
						need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
						accountBook: accountBook
					},
					success: (res) => {
						// 重置账本数据，进行查询
						if (vk.myfn.isNotEmpty(res.statements)) {
							that.statements = res.statements
						}
					},
					fail: (err) => {
						const msg = "删除失败-" + err.msg
						vk.alert(msg, "错误提示");
					}
				});
			},
			async enqrBookDataList() {
				const that = this
				const accountBook = this.allAccountBooks[this.selectAccountBookIndex]
				const pagination = {
					"pageIndex": vk.getVuex('$accountKeepData.enqrDataByPage.pagination.pageIndex') + 1,
					"pageSize": vk.getVuex('$accountKeepData.enqrDataByPage.pagination.pageSize')
				}
				await vk.callFunction({
					url: 'client/accounting/record/kh/getBookDataList',
					title: '请求中...',
					data: {
						need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
						pagination: pagination,
						accountBook: accountBook
					},
					success: (res) => {
						// 重置账本数据，进行查询
						this.$store.dispatch('$accountKeepData/enqrDataByPage', {
							res
						});
						this.dataList = vk.getVuex('$accountKeepData.dataList')
						this.enqrDataByPage= vk.getVuex('$accountKeepData.enqrDataByPage');
						console.log("dataList",this.dataList)
					},
					fail: (err) => {
						const msg = "查询失败-" + err.msg
						vk.alert(msg, "错误提示");
					}
				});
			},
			showDataDateMark(index){
				if(index === 0){
					return true
				}
				else if (this.dataList[index - 1].dataInf.date !== this.dataList[index].dataInf.date) {
					return true
				}
				else{
					return false
				}
			},
			getDateAmount(index, type){
				const firstIdx = this.getDateFirstIndex(index, true)
				const lastIdx = this.getDateFirstIndex(index, false)
				
				let amount = 0
				for (let i = firstIdx; i <= lastIdx; i++) {
					if(vk.myfn.isNotEmpty(this.dataList) && type === this.dataList[i].dataInf.isExpenses) {
						let _amount = this.dataList[i].dataInf.amount
						if(typeof _amount === 'string') {
							_amount = Number(_amount)
						}
						amount = amount + _amount
					}
				}
				amount = amount / 100
				return amount.toFixed(2);
			},
			getDateFirstIndex(index,firstMark){
				if(index === 0 && firstMark) {
					return index
				}
				else if (firstMark && vk.myfn.isNotEmpty(this.dataList) && vk.myfn.isNotEmpty(this.dataList[index - 1].dataInf) && vk.myfn.isNotEmpty(this.dataList[index].dataInf) 
				&& this.dataList[index - 1].dataInf.date === this.dataList[index].dataInf.date) {
					return this.getDateFirstIndex(index - 1, firstMark)
				}
				else if (!firstMark && vk.myfn.isNotEmpty(this.dataList) && index < (this.dataList.length - 1) && vk.myfn.isNotEmpty(this.dataList[index + 1].dataInf) && vk.myfn.isNotEmpty(this.dataList[index].dataInf) 
				 && this.dataList[index + 1].dataInf.date === this.dataList[index].dataInf.date) {
					return this.getDateFirstIndex(index + 1, firstMark)
				}
				else {
					return index
				}
			},
			reloadData(){
				// 获取已存在信息
				this.enqrDataByPage = vk.getVuex('$accountKeepData.enqrDataByPage') || null;
				// console.log("this.enqrDataByPage",this.enqrDataByPage)
				if (this.enqrDataByPage && (this.enqrDataByPage.data == null || this.enqrDataByPage.data.length == 0)) {
					// 查询
					this.enqrBookDataList()
				}
			},
			open() {},
			close() {
				this.show = false
				this.selectIndex = undefined
				this.selectData = undefined
			},
			selectDataBtn(index){
				this.selectIndex = index
				this.selectData = this.dataList[index]
				this.show = true
				console.log("this.selectData",this.selectData)
			},
			clickCardItem(type) {
				if(this.userInfo._id !== this.selectData.dataInf.uid) {
					vk.alert("非自身数据，不允许操作", "错误提示");
					return
				}
				if (type && type === 'del') {
					this.modelType = "del";
					this.modal.content = "确认删除本条记录么？";
					this.showModal = true;
				}
				else if (type && type === 'edit') {
					this.editData()
				}
			},
			closeModal() {
				this.showModal = false;
			},
			confirmModal() {
				if (this.modelType === "del") {
					this.delKeepingData()
				}
			},
			editData(){
				vk.setVuex("$accountKeepData.selectKeepData",{
					...this.selectData.dataInf,
					icon : {
						icon: this.selectData.dataInf.icon,
						name: this.selectData.dataInf.iconName
					},
					checkBookName:[this.accountBook.accountBookName]
				})
				vk.myfn.gotoPage('/pages/accounting/record/update','navigate')
			},
			async delKeepingData(){
				const that = this
				console.log(this.selectData)
				await vk.callFunction({
					url: 'client/accounting/record/kh/delKeepingData',
					title: '请求中...',
					data: {
						need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
						accountBook: this.accountBook,
						relationId: this.selectData._id,
						dataInf:  this.selectData.dataInf,
					},
					success: async (res) => {
						// 关闭
						this.show = false
						this.showModal = false;
						// 重置账本数据，进行查询
						this.$store.dispatch('$accountKeepData/enqrDataByPage', {
							res
						});
						await this.$store.dispatch('$accountKeepData/clearEnqrData');
						await this.enqrBookDataList();
						await this.enqrStatements()
						await this.enqrAllAccountBook()
					},
					fail: (err) => {
						const msg = "查询失败-" + err.msg
						vk.alert(msg, "错误提示");
					}
				});
			},
			async enqrAllAccountBook() {
				let that = this
				const pagination = {
					"pageIndex": 1,
					"pageSize": 1000
				}
				await vk.callFunction({
					url: 'client/accountbook/kh/enqrAccountBook',
					title: '请求中...',
					data: {
						need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
						pagination: pagination
					},
					success: async (res) => {
						await that.$store.dispatch('$accountbook/enqrAccountBook', {
							res
						});
						that.allAccountBooks= vk.getVuex('$accountbook.allAccountBooks');
					},
					fail: (err) => {
						const msg = "查询账本失败-" + err.msg
						vk.alert(msg, "错误提示");
					}
				});
			},
			
		}
	}
</script>
<style lang="scss" scoped>

</style>